浏览量 4195
2014/03/02 18:00
server
package echo;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class EchoServer {
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket ss;
try {
ss = new ServerSocket(8000);
System.out.println("Server already start!");
Boolean flag=true;
while(flag){
System.out.println("Wait........");
Socket s=ss.accept();
new Thread(new UserThread(s)).start();
}} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class UserThread implements Runnable{
private Socket s;
public UserThread(Socket s){
this.s=s;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
System.out.println(s.getInetAddress().getHostAddress()+"Client connected.");
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintStream ps=new PrintStream(new BufferedOutputStream(s.getOutputStream()));
boolean bool=true;
while(bool){
String it =br.readLine();
if("".equals(it)||"bye".equals(it)){
bool=false;
}else{
System.out.println(it);
ps.println("echo:"+it);
ps.flush();
}
}
ps.close();
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
client
package echo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class EchoClient {
public static void main(String[] args) {
try {
Socket s=new Socket("192.168.1.107",8000);
System.out.println("With server connected.");
Scanner input=new Scanner(System.in);
Boolean flag=true;
PrintStream ps=new PrintStream(new BufferedOutputStream(s.getOutputStream()));
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
while(flag){
System.out.println("Please input:");
String info=input.next();
if("bye".equals(info)){
flag=false;
}else{
ps.println(info);
ps.flush();
System.out.println( br.readLine());
}
}
ps.close();
br.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
上一篇 搜索 下一篇